package sfsoftware.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.newdawn.slick.util.ResourceLoader;

public class FileUtils 
{

    public static String[] fileToStringArray(String filename) throws IOException
    {
        //FileReader fileReader = new FileReader(filename);
        InputStreamReader fileReader = new InputStreamReader(ResourceLoader.getResourceAsStream(filename));
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) 
        {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
    
    public static String[] getResourceListing(String path, String type) throws IOException, URISyntaxException
    {
    	if(!(path.endsWith("/")))
    	{
    		path = path + "/";
    	}
    	Collection<URL> elements = ClasspathHelper.elementsOfFolder(path, type);
    	//System.out.println("$$$ " + elements.size() + " objects ending with " + type + " @ " + path);
    	List<String> resources = new ArrayList<String>();
    	
    	for(URL url: elements)
    	{
    		String fileName = url.getFile().toString();
    		fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());    		
    		//System.out.println("### " + fileName);
    		resources.add(fileName);
    	}    	
    	
    	return resources.toArray(new String[resources.size()]);
    } 
    
    public static void writeToFile(String file, String text)
    {
    	try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) 
    	{
    	    out.println(text);
    	}
    	catch (IOException e) 
    	{
    	    //exception handling left as an exercise for the reader
    	}    	
    }
}